package cn.easier.activity.console.utils;

import com.jcraft.jsch.*;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class DataSubmissionUtil {

    private static Logger logger = LoggerFactory.getLogger(DataSubmissionUtil.class);

    private static final int BUFFER_SIZE = 2 * 1024;

    private static Channel channel = null;

    private static Session sshSession = null;

    private static String hostName = "111.202.245.140";

    private static int port = 10002;

    private static String userName = "sjzt_mail";

    private static String password = "mail9087Ltzx_7612!@#";

    public static final int BUFFER = 1024;

    public static final CharSequence EXT = ".bz2";

    /**
     * 数据压缩
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] compress(byte[] data) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 压缩
        compress(bais, baos);
        byte[] output = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();
        return output;
    }

    /**
     * 文件压缩
     *
     * @param file
     * @throws Exception
     */
    public static void compress(File file) throws Exception {
        compress(file, true);
    }

    /**
     * 文件压缩
     *
     * @param file
     * @param delete 是否删除原始文件
     * @throws Exception
     */
    public static String compress(File file, boolean delete) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        String returnFilePath = file.getPath() + EXT;
        FileOutputStream fos = new FileOutputStream(file.getPath() + EXT);
        compress(fis, fos);
        fis.close();
        fos.flush();
        fos.close();
        if (delete) {
            file.delete();
        }
        return returnFilePath;
    }

    /**
     * 数据压缩
     *
     * @param is
     * @param os
     * @throws Exception
     */
    public static void compress(InputStream is, OutputStream os)
            throws Exception {
        BZip2CompressorOutputStream gos = new BZip2CompressorOutputStream(os);
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = is.read(data, 0, BUFFER)) != -1) {
            gos.write(data, 0, count);
        }
        gos.finish();
        gos.flush();
        gos.close();
    }

    /**
     * 文件压缩
     *
     * @param path
     * @throws Exception
     */
    public static String compress(String path) throws Exception {
        String returnFilePath = compress(path, true);
        return returnFilePath;
    }

    /**
     * 文件压缩
     *
     * @param path
     * @param delete 是否删除原始文件
     * @throws Exception
     */
    public static String compress(String path, boolean delete) throws Exception {
        File file = new File(path);
        String returnFilePath = compress(file, delete);
        return returnFilePath;
    }

    /**
     * 数据解压缩
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static byte[] decompress(byte[] data) throws Exception {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 解压缩
        decompress(bais, baos);
        data = baos.toByteArray();
        baos.flush();
        baos.close();
        bais.close();
        return data;
    }

    /**
     * 文件解压缩
     *
     * @param file
     * @throws Exception
     */
    public static void decompress(File file) throws Exception {
        decompress(file, true);
    }

    /**
     * 文件解压缩
     *
     * @param file
     * @param delete 是否删除原始文件
     * @throws Exception
     */
    public static void decompress(File file, boolean delete) throws Exception {
        FileInputStream fis = new FileInputStream(file);
        FileOutputStream fos = new FileOutputStream(file.getPath().replace(EXT,
                ""));
        decompress(fis, fos);
        fis.close();
        fos.flush();
        fos.close();

        if (delete) {
            file.delete();
        }
    }

    /**
     * 数据解压缩
     *
     * @param is
     * @param os
     * @throws Exception
     */
    public static void decompress(InputStream is, OutputStream os)
            throws Exception {
        BZip2CompressorInputStream gis = new BZip2CompressorInputStream(is);
        int count;
        byte data[] = new byte[BUFFER];
        while ((count = gis.read(data, 0, BUFFER)) != -1) {
            os.write(data, 0, count);
        }

        gis.close();
    }

    /**
     * 文件解压缩
     *
     * @param path
     * @throws Exception
     */
    public static void decompress(String path) throws Exception {
        decompress(path, true);
    }

    /**
     * 文件解压缩
     *
     * @param path
     * @param delete 是否删除原始文件
     * @throws Exception
     */
    public static void decompress(String path, boolean delete) throws Exception {
        File file = new File(path);
        decompress(file, delete);
    }

    /**
     * 上传
     *
     * @return
     */
    public static boolean upload(File file, String updateType, String fileType) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String workingPathTime = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
        String nameTime = new SimpleDateFormat("yyMMdd").format(cal.getTime());
        String workingPath = "/input/HY/" + workingPathTime + "/";
        String workingPathOne = "/input/HY/";
        String saveName;
        if (fileType.equals("MD5File")) {
            saveName = "CDBHYDWAL0" + updateType + "A" + nameTime + "1000000.000.MD5";
        } else {
            saveName = "CDBHYDWAL0" + updateType + "A" + nameTime + "1000000.000";
        }
        boolean flag = false;
        SFTP s = new SFTP();
        //1 测试连接
        if (connect(s)) {
            Session session = s.getSession();
            Channel channel = s.getChannel();
            ChannelSftp sftp = s.getSftp();// sftp操作类
            try {
                //逐级判断是否有这个目录 没有就创建
                createWorkingPath(sftp, workingPathOne);
                createWorkingPath(sftp, workingPath);
                InputStream fileInputStream = new FileInputStream(file);
                sftp.put(fileInputStream, saveName);
                fileInputStream.close();
            } catch (Exception e) {
                throw new Exception(e.getMessage(), e);
            } finally {
                disConn(session, channel, sftp);
            }
        }
        return flag;
    }

    /**
     * 断开连接
     */
    public static void disConn(Session session, Channel channel, ChannelSftp sftp) throws Exception {
        if (null != sftp) {
            sftp.disconnect();
            sftp.exit();
            sftp = null;
        }
        if (null != channel) {
            channel.disconnect();
            channel = null;
        }
        if (null != session) {
            session.disconnect();
            session = null;
        }
    }

    /**
     * 测试是否能连接
     */
    public static boolean connect(SFTP s) {
        boolean flag = false;
        try {
            JSch jsch = new JSch();
            sshSession = jsch.getSession(userName, hostName, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            try {
                sshSession.connect();
            } catch (Exception e) {
                if (sshSession.isConnected())
                    sshSession.disconnect();
                logger.error("连接服务器失败,请检查主机[" + hostName + "],端口[" + port
                        + "],用户名[" + userName + "],端口[" + port
                        + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
            }
            channel = sshSession.openChannel("sftp");
            try {
                channel.connect();
            } catch (Exception e) {
                if (channel.isConnected())
                    channel.disconnect();
                logger.error("连接服务器失败,请检查主机[" + hostName + "],端口[" + port
                        + "],用户名[" + userName + "],密码是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
            }
            //
            s.setChannel(channel);
            s.setSession(sshSession);
            ChannelSftp sftp = (ChannelSftp) channel;
            s.setSftp(sftp);
            return true;
        } catch (Exception e) {
            logger.error("连接失败，可能ip或端口错误");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 压缩成ZIP 方法1
     *
     * @param sourceDir        压缩文件夹路径
     * @param targetDir        压缩后文件的路径名称
     * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public String toZip(String sourceDir, String targetDir, boolean KeepDirStructure)
            throws RuntimeException {
        File sourceFile = new File(sourceDir);
        String sourcePath = sourceFile.getParentFile().toString();
        String fileName = sourceFile.getName();
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        String returnPath = null;
        try {
            FileOutputStream out = null;
            if (StringUtils.isEmpty(targetDir)) {
                if (sourceFile.isDirectory()) {
                    out = new FileOutputStream(new File(sourcePath + "/" + fileName + ".zip"));
                    returnPath = sourcePath + "/" + fileName + ".zip";
                } else {
                    out = new FileOutputStream(new File(sourcePath + "/" + fileName.substring(0, fileName.lastIndexOf('.')) + ".zip"));
                    returnPath = sourcePath + "/" + fileName.substring(0, fileName.lastIndexOf('.')) + ".zip";
                }
            } else {
                out = new FileOutputStream(new File(targetDir));
            }
            zos = new ZipOutputStream(out);
            compress(sourceFile, zos, sourceFile.getName(), KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return returnPath;
    }

    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if (KeepDirStructure) {
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }

            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(), KeepDirStructure);
                    }
                }
            }
        }
    }

    /**
     * 辅助方法
     *
     * @param filename
     * @return
     */
    private static byte[] createChecksum(String filename) {
        InputStream fis = null;
        try {
            fis = new FileInputStream(filename);
            byte[] buffer = new byte[1024];
            MessageDigest complete = MessageDigest.getInstance("MD5");
            int numRead = -1;

            while ((numRead = fis.read(buffer)) != -1) {
                complete.update(buffer, 0, numRead);
            }
            return complete.digest();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    /**
     * 生成文件的MD5码
     *
     * @param filePath 文件路径
     * @return 该文件的MD5码
     */
    private static String generateMD5(String filePath) {
        if (!new File(filePath).isFile()) {
            System.err.println("Error: " + filePath
                    + " is not a valid file.");
            return null;
        }
        byte[] b = createChecksum(filePath);
        if (null == b) {
            System.err.println(("Error:create md5 string failure!"));
            return null;
        }
        StringBuilder result = new StringBuilder();

        for (int i = 0; i < b.length; i++) {
            result.append(Integer.toString((b[i] & 0xff) + 0x100, 16)
                    .substring(1));
        }
        return result.toString();
    }

    private static void createWorkingPath(ChannelSftp sftp, String workingPath) throws Exception {
        try {
            sftp.cd(workingPath); //进入目录
        } catch (SftpException sException) {
            if (sftp.SSH_FX_NO_SUCH_FILE == sException.id) { //指定上传路径不存在
                sftp.mkdir(workingPath);//创建目录
                sftp.cd(workingPath);  //进入目录
            }
        }
    }

    /**
     * 根据文件，在同一文件夹下生成相应的MD5文件，文件名相同，仅后缀名不同
     * 比如文件为helloworld.txt，生成MD5文件：helloworld.md5
     *
     * @param filePath 文件绝对路径
     */
    public static String generateMD5File(String filePath) throws IOException {
        //获得该文件实例
        File file = new File(filePath);

        //获得该文件的MD5码
        String md5code = generateMD5(filePath);

        //获得该文件的文件夹路径
        String directoryPath = file.getParentFile().getAbsolutePath();

        //生成该文件对应的MD5文件的文件名
        String md5FileName = file.getName().substring(0, file.getName().lastIndexOf(".")) + ".MD5";

        //获得该文件对应的MD5文件的绝对路径
        String md5FilePath = directoryPath + File.separator + md5FileName;

        //生成MD5文件
        File md5File = new File(md5FilePath);
        if (!md5File.exists()) {
            md5File.createNewFile();
        }

        //文件写入MD5码的FileWriter类
        FileWriter fileWriter = new FileWriter(md5File);
        //将MD5码写入到MD5文件中
        fileWriter.write(md5code);
        //刷新流
        fileWriter.flush();
        //关流
        fileWriter.close();

        //打印提示信息
        System.out.println("创建MD5文件成功：" + md5FilePath);
        return md5FilePath;
    }


    /**
     * 输入文件夹名称，将该文件夹下所有的文件都生成同名的MD5文件
     *
     * @param directoryPath
     */
    public static void generateMD5Files(String directoryPath) throws IOException {
        //创建文件夹实例
        File directory = new File(directoryPath);
        //文件数组
        File[] files = null;

        if (directory.isDirectory()) {
            //获得所有文件
            files = directory.listFiles();
            //分别为每一个文件创建MD5文件
            for (int i = 0; i < files.length; i++) {
                generateMD5File(files[i].getAbsolutePath());
            }
        } else {
            System.err.println("不是文件夹，请检查路径！");
            return;
        }

    }
        //输入文件的绝对路径，生成该文件同一文件夹下的相同文件名，后缀名为.md5的文件
        //generateMD5File("C:\\Users\\李小白\\Desktop\\MD5\\helloworld.txt");
        //输入文件夹的绝对路径，生成该文件夹下所有文件的MD5文件，该文件夹的文件数多一倍
        //generateMD5Files("C:\\Users\\李小白\\Desktop\\MD5");
}
